package com.itheima.controller;


import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController  //  二合一
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 查全部
    @GetMapping
    public Result getAll() {
        return new Result(Code.GET_OK, "查询成功",
                bookService.getAll());
    }

    // 按照id 查询
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {

        if (id == 1) {
            int i = 1 / 0;
        } else if (id == 2) {
            throw new BusinessException(Code.BUSINESS_ERR, "我异常了  请规范书写");
        } else if (id == 3){
            throw new SystemException(Code.SYSTEM_ERR, "我异常了  系统异常");
        }

        return new Result(Code.GET_OK, "查询成功",
                bookService.getBuId(id));
    }

    // 新增
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean b = bookService.save(book);
        return new Result(b ? Code.SAVE_OK : Code.SAVE_ERR,
                b ? "添加成功" : "添加失败", book);
    }

    // 修改
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean b = bookService.update(book);
        return new Result(b ? Code.UPDATE_OK : Code.UPDATE_ERR,
                b ? "修改成功" : "修改失败", book);
    }

    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = bookService.delete(id);
        return new Result(b ? Code.DELETE_OK : Code.DELETE_ERR,
                b ? "删除成功" : "删除失败",
                null);
    }


}
